import datetime
import re


def output(out, line):
    out.write(",".join(line) + "\n")


if __name__ == '__main__':

    source = open("data.csv", encoding='utf-8')
    new_data = open("newdata.csv", "w+")

    date_map = {}
    stock_map = {}

    # 1.数据预处理，获取每个stock的所有交易数据

    source = source.readlines()

    for line in source:
        line = line.replace("\n", "").split(",")

        line[0] = re.findall("[0-9]+", line[0])[0]

        date = line[1].split("/")
        year = int(date[0])
        month = int(date[1])
        day = int(date[2])
        datetime_date = datetime.date(year, month, day)
        while datetime_date.weekday() != 4:
            datetime_date = datetime_date.__add__(datetime.timedelta(days=1))
        friday = "%d/%02d/%02d" % (datetime_date.year, datetime_date.month, datetime_date.day)
        line[1] = friday

        stock_list = stock_map.get(line[0], [])
        stock_list.append(line)
        stock_map[line[0]] = stock_list
        date_map[friday] = 1

    for stock in stock_map:
        # 将每一个stock的所有数据按日期排序
        stock_list = list(sorted(stock_map[stock], key=lambda x: x[1]))

        last_line = None
        for stock_line in stock_list:
            if last_line is None:
                last_line = stock_line

                # 先把上一条数据输出，每次只处理当前数据
                output(new_data, last_line)
                continue

            while last_line[1] != stock_line[1]:  # 第一次肯定不相等
                date = last_line[1].split("/")
                year = int(date[0])
                month = int(date[1])
                day = int(date[2])
                datetime_date = datetime.date(year, month, day).__add__(datetime.timedelta(days=7))
                last_line[1] = "%d/%02d/%02d" % (datetime_date.year, datetime_date.month, datetime_date.day)
                last_line[4] = "0"

                # 新日期是交易日，但不是当前日，输出原先的价格，并且盈利率为0
                if last_line[1] in date_map and last_line[1] != stock_line[1]:
                    output(new_data, last_line)
                elif last_line[1] == stock_line[1]:
                    # 如果新日期是当前日，则输出当前日，并且更新last_line
                    last_line = stock_line
                    output(new_data, stock_line)
